package com.fanxj.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fanxj.Utils.JWTUtils;
import com.fanxj.Utils.OSSService;
import com.fanxj.Utils.ResponseData;
import com.fanxj.domain.*;
import com.fanxj.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/User")
public class UserController {
   @Autowired
    private UserService userService;
    @Autowired
    private OSSService ossService;
   //登录
    @RequestMapping(value = "/login",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData login(User userLogin){
         User user=userService.findByUser(userLogin);
        boolean login=false;
        ResponseData responseData=null;
        if(user!=null){
           login=true;
           responseData = ResponseData.ok();
        }
        if(login) {
            //生成token
            String token = JWTUtils.generateToken("1",user.getUsername(), user.getPassword());
            //向浏览器返回token，客户端受到此token后存入cookie中，或者h5的本地存储中
            responseData.putDataValue("token", token);
            //以及用户
            responseData.putDataValue("user", user);
        }else {
            //用户或者密码错误
            responseData=ResponseData.customerError();
        }
        return responseData;
    }

    //注册
    @RequestMapping(value = "/register",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData register(User userRegister){
        String message=userService.saveUser(userRegister);
        System.out.println(message);
        ResponseData responseData=null;
        if(message.equals("success")){
            responseData = ResponseData.ok();
        }else{
            responseData = ResponseData.UserExist();
        }
        return responseData;
    }

    @RequestMapping(value = "/searchDecade",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData searchDecade(){
        List<DecadeType>  decadeTypeList=userService.findDecadeType();
        ResponseData responseData = ResponseData.ok();
        responseData.putDataValue("decadeTypeList", decadeTypeList);
        return responseData;
    }

    @RequestMapping(value = "/searchLocal",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData searchLocal(){
        List<LocalType>  localTypeList=userService.findLocalType();
        ResponseData responseData = ResponseData.ok();
        responseData.putDataValue("LocalTypeList", localTypeList);
        return responseData;
    }


    @RequestMapping(value = "/searchTypes",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData searchTypes(){
        List<GroupType>  groupTypeList=userService.findGroupType();
        ResponseData responseData = ResponseData.ok();
        responseData.putDataValue("groupTypeList", groupTypeList);
        return responseData;
    }

    @RequestMapping(value = "/searchRelics",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData searchRelics(SortParams sortParams){
        String signature = ossService.generateOssSignature();
        //获取筛选传参分类编号
        String decadeTypeCode =sortParams.getDecadeType();
        String groupTypeCode =sortParams.getGroupType();
        String localTypeCode =sortParams.getLocalType();
        //获取编号对应的分类对象
        DecadeType  decadeType=userService.findDecadeTypeByCode(decadeTypeCode);
        GroupType  groupType=userService.findGroupTypeByCode(groupTypeCode);
        LocalType localType=userService.findLocalTypeByCode(localTypeCode);
        //把查出来的分类对象分别放入params对象中
        Params params = new Params();
        String label=decadeType.getLabel();
        decadeType.setLabel(label+'%');
        params.putParamsValue("decadeType",decadeType);
        params.putParamsValue("groupType",groupType);
        params.putParamsValue("localType",localType);
        List<Relic> relics=userService.findRelic(params);
        ResponseData responseData = ResponseData.ok();
        responseData.putDataValue("relics", relics);
        responseData.putDataValue("total", relics.size());
        responseData.putDataValue("signature", signature);

        return responseData;
    }
    @RequestMapping(value = "/collectionRelic",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData collectionRelic(CollectionRelic crelic){
      CollectionRelic isExitcollectionRelic= userService.IsExitcollectionRelic(crelic);
        ResponseData responseData =null;
        if(isExitcollectionRelic!=null)
            responseData = ResponseData.CollectionExist();
        else{
            userService.collectionRelic(crelic);
            responseData = ResponseData.ok();
        }

        return responseData;
    }

    @RequestMapping(value = "/searchCollection",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData searchCollection(User user){
        List<Relic> collections=userService.searchCollection(user);
        ResponseData responseData = ResponseData.ok();
        responseData.putDataValue("collections", collections);
        responseData.putDataValue("total", collections.size());
        return responseData;
    }


    @RequestMapping(value = "/deleteCollection",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData deleteCollection(DeleteCollection delCollection){
        userService.deleteCollection(delCollection);
        System.out.println(delCollection);
        ResponseData responseData = ResponseData.ok();
        return responseData;
    }


    @RequestMapping(value = "/SearchCollectionRelic",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData SearchCollectionRelic(SearchPersonRelics searchPerson){
        String s="%"+searchPerson.getSearchValue()+"%";
        searchPerson.setSearchValue(s);
        List<Relic> relicList=userService.SearchCollectionRelic(searchPerson);
        System.out.println(searchPerson);
        ResponseData responseData = ResponseData.ok();
        responseData.putDataValue("relicList",relicList);
        return responseData;
    }


    @RequestMapping(value = "/Search",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData Search(String searchValue){
        ResponseData responseData ;
        String likeName="%"+searchValue+"%";
        DecadeType  decadeType=userService.findDecadeTypeByLabel(likeName);
        GroupType  groupType=userService.findGroupTypeByLabel(likeName);
        LocalType localType=userService.findLocalTypeByLabel(likeName);
        if(decadeType!=null||groupType!=null||localType!=null){
          try{
              if(decadeType==null) {
                  decadeType=new DecadeType(1,"全部","0");
              }else{
                  decadeType.setLabel('%'+decadeType.getLabel()+'%');
              }
              if(groupType==null) {
                  groupType=new GroupType(1,"全部","0");
              }
              if(localType==null) {
                  localType=new LocalType(1,"全部","0");
              }
          }catch(Exception e){
              e.printStackTrace();
          }
            //把查出来的分类对象分别放入params对象中
            Params params = new Params();
            params.putParamsValue("decadeType",decadeType);
            params.putParamsValue("groupType",groupType);
            params.putParamsValue("localType",localType);
            List<Relic> relics=userService.findRelic(params);
            responseData = ResponseData.ok();
            responseData.putDataValue("relicList",relics);
        } else{
            List<Relic> relicList=userService.Search(likeName);
            responseData = ResponseData.ok();
            responseData.putDataValue("relicList",relicList);
        }
        return responseData;
    }

    @RequestMapping(value = "/Recommend",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData Recommend(String name,String groupType){
        Params params=new Params();
        params.putParamsValue("name",name);
        params.putParamsValue("groupType",groupType);
        List<Relic> relicList=userService.Recommend(params);
        ResponseData responseData = ResponseData.ok();
        responseData.putDataValue("relicList",relicList);
        return responseData;
    }

    @RequestMapping(value = "/uploadHeadImage",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public ResponseData uploadHeadImage(@RequestParam("file") MultipartFile file, @RequestParam("username")String username, @RequestParam("image")String image) throws IOException {
        ResponseData responseData = null;
        if (file.isEmpty()) {
            responseData = ResponseData.notFound();
            return responseData;
        }
        if(!("null".equals(image))){
            String newString = image.replaceFirst("^/", "");
            ossService.deleteFile(newString);
        }
        String fileUrl = ossService.uploadFile(file);
        Params params = new Params();
        params.putParamsValue("username",username);
        params.putParamsValue("image",fileUrl);
        userService.uploadHeadImage(params);
        if (fileUrl != null) {
            responseData= ResponseData.ok(); // 返回文件的URL
            responseData.putDataValue("fileUrl", fileUrl);
        } else {
            responseData=ResponseData.customerError();
        }
        return responseData;
    }

    @RequestMapping(value = "/updatePassword",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  ResponseData updatePassword(String username,String oldPassword,String newPassword){
        User user=new User();
        user.setUsername(username);
        user.setPassword(oldPassword);
        ResponseData responseData =null;
       User oldUser=userService.findByUser(user);
       System.out.println(oldUser);
        if(oldUser!=null){
            if(oldPassword.equals(newPassword)){
                String message="新密码与旧密码不能相同！";
                responseData = ResponseData.Error();
                responseData.putDataValue("message",message);
            }
            else{
                Params params=new Params();
                params.putParamsValue("username",username);
                params.putParamsValue("newPassword",newPassword);
                userService.updatePassword(params);
                responseData = ResponseData.ok();
            }
        }
        else{
            responseData = ResponseData.Error();
            String message="旧密码输入不正确，请重新输入！";
            responseData.putDataValue("message",message);
        }
        return responseData;
    }

}
